var date = new Date;
var yearNext = date.getFullYear() + 1;
var year = date.getFullYear() + " - " + yearNext;
var orgSelect = "";

/*柱状图*/

var province = "", city = "", area = "", road = "";


var barChartOptions = {
    //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
    scaleBeginAtZero: true,
    //Boolean - Whether grid lines are shown across the chart
    scaleShowGridLines: true,
    //String - Colour of the grid lines
    scaleGridLineColor: "rgba(0,0,0,.05)",
    //Number - Width of the grid lines
    scaleGridLineWidth: 1,
    //Boolean - Whether to show horizontal lines (except X axis)
    scaleShowHorizontalLines: true,
    //Boolean - Whether to show vertical lines (except Y axis)
    scaleShowVerticalLines: true,
    //Boolean - If there is a stroke on each bar
    barShowStroke: true,
    //Number - Pixel width of the bar stroke
    barStrokeWidth: 2,
    //Number - Spacing between each of the X value sets
    barValueSpacing: 5,
    //Number - Spacing between data sets within X values
    barDatasetSpacing: 1,
    //关闭提示
    showTooltips: false,
    //String - A legend template
    legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].fillColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>",
    //Boolean - whether to make the chart responsive
    responsive: true,
    maintainAspectRatio: true,
    onAnimationComplete: function () {
        var ctx = this.chart.ctx;
        ctx.font = this.scale.font;
        ctx.fillStyle = this.scale.textColor;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';
        this.datasets.forEach(function (dataset) {
            dataset.bars.forEach(function (bar) {
                ctx.fillText(bar.value, bar.x, bar.y);
            });
        });
    }
};
barChartOptions.datasetFill = false;

//标志分类统计柱状图
$.getSignCounts = function () {
    province = $("#provinceChoose").val();
    city = $("#cityChoose").val();
    area = $("#areaChoose").val();
    road = $("#roadChoose").val();
    $.ajax({
        url: '../rds_guardrailLocationCount/getGuardrailTypeCounts',
        type: 'post',
        data: {
            userId: gUserLoginResult.userId,
            orgId: $("#orgChoose").val(),
            time: year,
            province: province,
            city: city,
            area: area,
            road: road

        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var signCounts = [0, 0, 0, 0, 0];
                    var counts = msg.jsonData;
                    for (var i = 0; i < counts.length; i++) {
                        signCounts[counts[i]]++;
                    }
                    $("#word").html("护栏分类统计柱状图(" + counts.length + ")");
                    $("#barChart").remove();
                    $("#barChartParent").html("<canvas id='barChart' style='height:230px'></canvas>");
                    var areaChartData = {
                        //护栏类型 0:中央分隔带护栏; 1:机非分隔带护栏; 2:人行道隔离护栏; 3:公共汽车专用道护栏; 4:普通隔离护栏;
                        labels: ["中央分隔带护栏", "机非分隔带护栏", "人行道隔离护栏", "公共汽车专用道护栏", "普通隔离护栏"],
                        datasets: [
                            {
                                label: "Electronics",
                                fillColor: "#00c0ef",
                                strokeColor: "#00c0ef",
                                pointColor: "rgba(210, 214, 222, 1)",
                                pointStrokeColor: "#c1c7d1",
                                pointHighlightFill: "#fff",
                                pointHighlightStroke: "rgba(220,220,220,1)",
                                data: signCounts
                            }
                        ]
                    };
                    var barChartCanvas = $("#barChart").get(0).getContext("2d");
                    var barChart = new Chart(barChartCanvas);
                    var barChartData = areaChartData;
                    barChart.Bar(barChartData, barChartOptions);
                }
            }
        }
    });
};


//按维护单位查询的下拉框
$.getDealOrg = function () {
    $.ajax({
        url: '../rds_count/getDealOrg',
        type: 'post',
        data: {
            userId: gUserLoginResult.userId,
            orgId: gUserLoginResult.orgId
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    orgSelect = "<div class='input-group input-group-sm'><select class='form-control' id='orgChoose' onchange='$.getSignCounts();'> ";
                    if (msg.jsonData.length > 1) {
                        orgSelect += "<option value='-1'>维护公司</option>";
                    }
                    if (msg.jsonData.length == 0) {
                        orgSelect += "<option value='-1'>无权限</option>";
                    }
                    for (var i = 0; i < msg.jsonData.length; i++) {
                        orgSelect += "<option value='" + msg.jsonData[i].orgId + "'>" + msg.jsonData[i].orgName + "</option>";
                    }
                    orgSelect += "</select></div>";
                    $("#orgSelect").html(orgSelect);
                    if (gUserLoginResult.orgType == 0 && msg.jsonData.length == 1) {
                        $("#orgChoose").hide();
                    }
                    $.getSignCounts();
                }
            }
        }
    })
};


/*//Date picker
 $('#datepicker').datepicker({
 language: "zh-CN",
 format: 'yyyy',
 autoclose: true,
 startView: 'years',
 maxViewMode: 'years',
 minViewMode: 'years',
 }).on('hide', function (e) {
 year = $("#datepicker").val();
 $.getSignCounts();
 });

 //设置默认时间
 $('#datepicker').datepicker('setDate', new Date());
 $('#datepicker').datepicker('setEndDate', '2100');
 $('#datepicker').datepicker('setStartDate', '2000');*/
$("#timeLimit").focus(function () {
    $('#timeLimit').daterangepicker({
        autoUpdateInput: false,
        locale: {
            format: 'YYYY-MM-DD',
            applyLabel: '确认',
            cancelLabel: '取消',
            fromLabel: '从',
            toLabel: '到',
            weekLabel: 'W',
            customRangeLabel: 'Custom Range',
            daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
            monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        }
    }).on('cancel.daterangepicker', function (ev, picker) {

    }).on('apply.daterangepicker', function (ev, picker) {
        $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
        year = $("#timeLimit").val();
    });
    $(".dropdown-menu").css("min-width", "0");
});

/*******************************************************/

//按省份查询的下拉框
$.getProvinceName = function () {
    $.ajax({
        url: '../rds_guardrailLocationCount/getProvinceName',
        type: 'post',
        data: {
            userId: gUserLoginResult.userId,
            orgId: gUserLoginResult.orgId
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    provinceSelect = "<option value='-1'>省份</option>";
                    var flag = 0;
                    for (var i = 0; i < msg.jsonData.length; i++) {
                        if (msg.jsonData[i] == "" || msg.jsonData[i] == null) {
                            if (flag == 0) {
                                provinceSelect += "<option value=''>未知省份</option> ";
                                flag = 1;
                            }
                        }
                        else
                            provinceSelect += "<option value='" + msg.jsonData[i] + "'>" + msg.jsonData[i] + "</option>";
                    }
                    provinceSelect += "";
                    $("#provinceChoose").append(provinceSelect);
                }
            }
        }
    });
};

//按市查询的下拉框
$.getCityName = function (provinceName) {
    $.ajax({
        url: '../rds_guardrailLocationCount/getCityName',
        type: 'post',
        data: {
            userId: gUserLoginResult.userId,
            orgId: gUserLoginResult.orgId,
            provinceName: provinceName
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    citySelect = "<option value='-1'>市</option>";
                    var flag = 0;
                    for (var i = 0; i < msg.jsonData.length; i++) {
                        if (msg.jsonData[i] == "" || msg.jsonData[i] == null) {
                            if (flag == 0) {
                                citySelect += "<option value=''>未知市</option> ";
                                flag = 1;
                            }
                        }
                        else
                            citySelect += "<option value='" + msg.jsonData[i] + "'>" + msg.jsonData[i] + "</option>";
                    }
                    $("#cityChoose").html(citySelect);
                }
            }
        }
    });
};

//按区域查询的下拉框
$.getAllAreaName = function (provinceName, cityName) {
    $.ajax({
        url: '../rds_guardrailLocationCount/getAllAreaName',
        type: 'post',
        data: {
            userId: gUserLoginResult.userId,
            orgId: gUserLoginResult.orgId,
            provinceName: provinceName,
            cityName: cityName
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    areaSelect = "<option value='-1'>区域</option>";
                    var flag = 0;
                    for (var i = 0; i < msg.jsonData.length; i++) {
                        if (msg.jsonData[i] == "" || msg.jsonData[i] == null) {
                            if (flag == 0) {
                                areaSelect += "<option value=''>未知区域</option> ";
                                flag = 1;
                            }
                        }
                        else
                            areaSelect += "<option value='" + msg.jsonData[i] + "'>" + msg.jsonData[i] + "</option>";
                    }
                    $("#areaChoose").html(areaSelect);
                }
            }
        }
    });
};

//按道路查询的下拉框
$.getAllRoadName = function (provinceName, cityName, areaName) {
    $.ajax({
        url: '../rds_guardrailLocationCount/getAllRoadName',
        type: 'post',
        data: {
            userId: gUserLoginResult.userId,
            orgId: gUserLoginResult.orgId,
            provinceName: provinceName,
            cityName: cityName,
            areaName: areaName
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    roadSelect = "<option value='-1'>道路</option>";
                    var flag = 0;
                    for (var i = 0; i < msg.jsonData.length; i++) {
                        if (msg.jsonData[i] == null || msg.jsonData[i].length == 0) {
                            if (flag == 0) {
                                roadSelect += "<option value=''>未知道路</option>";
                                flag = 1;
                            }
                        }
                        else
                            roadSelect += "<option value='" + msg.jsonData[i] + "'>" + msg.jsonData[i] + "</option>";
                    }
                    $("#roadChoose").html(roadSelect);
                }
            }
        }
    });
};

//按主管单位查询的下拉框
$.getAllOrg = function () {
    $.ajax({
        url: '../rds_count/getAllOrg',
        type: 'post',
        data: {
            userId: gUserLoginResult.userId,
            orgId: gUserLoginResult.orgId
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    orgSelect = "<div class='input-group input-group-sm'>";
                    if (gUserLoginResult.orgType == 1 && msg.jsonData.length == 1) {
                        orgSelect += "<select class='form-control' id='orgChoose' style='display: none'> <option value='-1'>主管单位</option>";
                    }
                    else if (gUserLoginResult.orgType == 0 && msg.jsonData.length == 0) {
                        orgSelect += "<select class='form-control' id='orgChoose' style='display: none'> <option value='-1'>主管单位</option>";
                    }
                    else {
                        orgSelect += "<select class='form-control' id='orgChoose' style='width: 150px'> <option value='-1'>主管单位</option>";
                    }
                    for (var i = 0; i < msg.jsonData.length; i++) {
                        orgSelect += "<option value='" + msg.jsonData[i].orgId + "'>" + msg.jsonData[i].orgName + "</option>";
                    }
                    orgSelect += "</select></div>";
                    $("#htmlOrgSelect").html(orgSelect);
                }
            }
        }
    });
};

//按维护单位查询的下拉框
$.getConservationOrg = function (mainOrgId) {
    $.ajax({
        url: '../rds_count/getConservationOrg',
        type: 'post',
        data: {
            mainOrgId: mainOrgId,
            userId: gUserLoginResult.userId,
            orgId: gUserLoginResult.orgId
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    if (msg != null && typeof (msg) != "undefined") {
                        if (msg.isSuccess == true) {
                            orgConservationSelect = '';
                            if (msg.jsonData.length > 1) {
                                orgConservationSelect = "<option value='-1'>养护公司</option>";
                            }
                            if (msg.jsonData.length == 0) {
                                orgConservationSelect = "<option value='-1'>无权限</option>";
                            }
                            for (var i = 0; i < msg.jsonData.length; i++) {
                                orgConservationSelect += "<option value='" + msg.jsonData[i].orgId + "'>" + msg.jsonData[i].orgName + "</option>";
                            }
                            orgConservationSelect += "</select>";
                            $("#orgConservationChoose").html(orgConservationSelect);
                            if (gUserLoginResult.orgType == 0 && msg.jsonData.length == 1) {
                                $("#orgConservationChoose").hide();
                            }
                        }
                    }
                }
            }
        }
    });
};


//省
$("#provinceChoose").change(function () {
    $.getCityName($("#provinceChoose").val());
    $.getAllAreaName($("#provinceChoose").val(), $("#cityChoose").val());
    $.getAllRoadName($("#provinceChoose").val(), $("#cityChoose").val(), $("#areaChoose").val());
});
//市
$("#cityChoose").change(function () {
    $.getAllAreaName($("#provinceChoose").val(), $("#cityChoose").val());
    $.getAllRoadName($("#provinceChoose").val(), $("#cityChoose").val(), $("#areaChoose").val());
});
//区
$("#areaChoose").change(function () {
    $.getAllRoadName($("#provinceChoose").val(), $("#cityChoose").val(), $("#areaChoose").val());
});


$("#yearBtn").on("click", function () {
    $("#timeLimit").val($("#timeLimit").val().substring(0, 4));
    var t = parseInt($("#timeLimit").val()) + 1;
    year = $("#timeLimit").val() + " - " + t;
});

$(function () {
    $.getProvinceName();
    $.getCityName(-1);
    $.getAllAreaName(-1, -1);
    $.getAllRoadName(-1, -1, -1);
    $.getConservationOrg(-1);
    $("#timeLimit").val(yearNext - 1);
    $.getDealOrg();
});

